package com.rrd.hive.udf.sms;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.IntWritable;

import static com.rrd.hive.udf.sms.HiveUdfRegexTools.hiveUdfRegExpEx;
import static com.rrd.hive.udf.sms.HiveUdfRegexTools.hiveUdfRegexResultToString;

@Description(
        name = "sms_get_sub_type",
        value = "_FUNC_(ip) - Get sub type of sms",
        extended = "Example:\n> SELECT _FUNC_('smsbody-代发工资-代发人民币12元');\n  0:bank 1:nonbank 2:other"
)
public class GetSubTypeUDF extends UDF {
    public static final String pattern1 = "电信|短信|微信|卡劵|移动|联通|通卡|社保卡|工信|旗舰店|同花|信息|信访|ETC|高速|自来水|飞信|通信|王卡|停机|连信|学信网|卫生|集享卡|迪卡侬";
    public static final String pattern2 = "银|贷|钱|金融|卡|普惠|分期|消金|现金|借|呗|花|信|金服|白条|农商行|金条|支付";
    public static final String pattern3 = "还款|应还|征信|逾期案件|分期|贷款|借|利息|利率|审批|下款|用款|综合评分";

    public static Configuration config() {
        System.setProperty("HADOOP_USER_NAME", "hdfs");
        Configuration conf = new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        return conf;
    }

    public static void main(String[] args) throws Exception {
        GetSubTypeUDF dfu = new GetSubTypeUDF();
        System.out.println(dfu.evaluate("smsbody-代发工资-代发人民币12元"));
    }

    public IntWritable evaluate(String smsBody) {
        IntWritable ret = new IntWritable(2); //other
        try {
            String pattern = "(^【.{0,10}】)|(【.{0,10}】$)|(^\\[.{0,10}\\])|(\\[.{0,10}\\]$)";
//            System.out.println("find res: " + hiveUdfRegExpEx(smsBody, pattern));

            String organ_name = hiveUdfRegexResultToString(smsBody, pattern);
            if(organ_name != null) {
                if(hiveUdfRegExpEx(organ_name, pattern1) == 0){
                    if(hiveUdfRegExpEx(organ_name,pattern2) == 1
                    || (organ_name != "" && hiveUdfRegExpEx(smsBody,pattern3) == 1)
                    ||(hiveUdfRegExpEx(organ_name, "逾期") == 1 && hiveUdfRegExpEx(organ_name, "法院") == 1)) {
                        if(hiveUdfRegExpEx(organ_name, "银行") == 1
                        ||hiveUdfRegExpEx(organ_name, "信用卡") == 1
                        ||hiveUdfRegExpEx(organ_name, "农商行") == 1) {
                            ret.set(0); //bank
                        } else {
                            ret.set(1); //nonbank
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Excep: " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            return ret;
        }
    }
}
